package com.jt.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jt.mapper.ItemDescMapper;
import com.jt.mapper.ItemMapper;
import com.jt.pojo.Item;
import com.jt.pojo.ItemDesc;
import com.jt.vo.ItemVO;
import com.jt.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class ItemServiceImpl implements ItemService{
    @Autowired
    private ItemMapper itemMapper;
    @Autowired
    private ItemDescMapper itemDescMapper;
/**
 * 1,手写Sql 一种写法
 * 2.利用Mp机制实现分页*/
    @Override
    @Transactional
    public PageResult getItemList(PageResult pageResult) {//3个
        IPage page = new Page(pageResult.getPageNum(),pageResult.getPageSize());
        QueryWrapper<Item> queryWrapper = new QueryWrapper<>();
        boolean flag = StringUtils.hasLength(pageResult.getQuery());
        queryWrapper.like(flag,"title",pageResult.getQuery());
        //执行分页查询，返回值依然是分页对象信息
        page = itemMapper.selectPage(page,queryWrapper);
        //回传5个
        long total = page.getTotal();
        List<Item> rows = page.getRecords();
        return pageResult.setTotal(total).setRows(rows);
    }

    @Override
    @Transactional
    public void updateItemStatus(Item item) {
        itemMapper.updateById(item);
    }

    @Override
    @Transactional
    public void deleteItemById(Integer id) {
        //删除商品表
        itemMapper.deleteById(id);
        //删除详情
        itemDescMapper.deleteById(id);
    }

    @Override
    @Transactional
    public void saveItem(ItemVO itemVO) {
        Item item = itemVO.getItem();
        item.setStatus(true);//默认启动状态
        itemMapper.insert(item);//MP自动实现回显
        ItemDesc itemDesc = itemVO.getItemDesc();
        itemDesc.setId(item.getId());//Mp回显之后取值操作
        itemDescMapper.insert(itemDesc);
    }

}
